package router

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"goKit/endpoint"
	"goKit/middleware"
	"goKit/transport"

	goKitHttp "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	"github.com/sirupsen/logrus"
)

var HttpOptions = []goKitHttp.ServerOption{
	// 请求解码之前，在HTTP请求对象上执行函数。
	goKitHttp.ServerBefore(func(ctx context.Context, request *http.Request) context.Context {
		ctx = context.WithValue(ctx, "timer", time.Now().UnixNano())
		ctx = context.WithValue(ctx, "url", fmt.Sprintf("request -- {%v} {%v}", request.RequestURI, request.Method))
		return ctx
	}),
	// 返回之前
	goKitHttp.ServerAfter(func(ctx context.Context, response http.ResponseWriter) context.Context {
		beginTime, ok1 := ctx.Value("timer").(int64)
		url, ok2 := ctx.Value("url").(string)
		if ok1 && ok2 {
			logrus.Info(url, " 耗时：", (time.Now().UnixNano()-beginTime)/1000000000, "s")
		}
		return ctx
	}),
	// 服务错误时，走这个
	goKitHttp.ServerErrorEncoder(func(ctx context.Context, err error, w http.ResponseWriter) {
		w.WriteHeader(http.StatusOK)
		encoder := json.NewEncoder(w)
		_ = encoder.Encode(err.Error())
		return
	}),
	// 和上面的这个有点相似，需要重写一个方法
	//goKitHttp.ServerErrorHandler(),
}

func ServiceForHttp(r *mux.Router) {
	getCode := goKitHttp.NewServer(
		middleware.JwtMiddleware()(endpoint.GenVcEndpoint()),
		transport.DecodeVcRequest,
		transport.EncodeVcResponse,
		HttpOptions...)
	input := goKitHttp.NewServer(
		endpoint.PostInputEndpoint(),
		transport.DecodeInputUserRequest,
		transport.EncodeVcResponse,
		HttpOptions...)

	groupUser := r.PathPrefix("/user").Subrouter() // 路由分组
	groupUser.Use(Xx)
	groupUser.Methods("Get").Path(`/getName/{uid:\d+}`).Handler(getCode)
	groupUser.Methods("POST").Path(`/input`).Handler(input)
}
func Xx(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 关于token的校验，我想放在这个地方做，但是又没想好要怎么做
		h.ServeHTTP(w, r)
	})
}
